import { createApp } from 'vue';
import App from './App.vue';
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';
import { createRouter, createWebHashHistory } from 'vue-router'; // 注意这里的导入方式
import Index from './pages/index.vue';
import Login from './pages/login.vue';
import Register from './pages/register.vue';
import './common/axios';
import 'bootstrap/dist/css/bootstrap.min.css';
import { initWebSocket, socket } from './common/websocket';
import { createPinia } from 'pinia';
import { useStore } from './common/piniaStore';
import ElementPlusCrx from "element-plus-crx";
const app = createApp(App);

// 使用 Pinia
app.use(createPinia());

// 初始化 Client 对象
const store = useStore();

// 安装 ElementPlus
app.use(ElementPlus);
app.use(ElementPlusCrx);
// 创建路由实例
const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/', // 根路径
      component: Index // 登录页组件
    },
    {
      path: '/index',
      component: Index
    },
    {
      path: '/login',
      component: Login
    },
    {
      path: '/register',
      component: Register
    }
  ]
});

router.beforeEach((to, _from, next) => {
  if (to.path === '/index') {
    //与服务器建立socket连接
    window.electron.ipcRenderer.on('user-info', (_, data) => {
      initWebSocket();
      store.initClient(socket);
      store.setUserId(data.userId);
      store.setName(data.name);
    });
  }
  next();
});

// 使用路由
app.use(router);
app.mount('#app');
